/*            Copyright(c) 2006-2008 Dave Sexton           *
 * http://www.codeplex.com/DocProject                      *
 * http://www.codeplex.com/DocProject/Project/License.aspx *
 ***********************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using DaveSexton.DocProject.Resources;
using Microsoft.VisualStudio.CommandBars;

namespace DaveSexton.DocProject
{
	public sealed class ToolWindowCollection : KeyedCollection<Guid, ToolWindow>
	{
		#region Constructors
		/// <summary>
		/// Constructs a new instance of the <see cref="ToolWindowCollection" /> class.
		/// </summary>
		public ToolWindowCollection()
		{
		}
		#endregion

		#region Methods
		protected override Guid GetKeyForItem(ToolWindow item)
		{
			return item.Guid;
		}

		protected override void InsertItem(int index, ToolWindow item)
		{
			if (item == null)
				throw new ArgumentNullException("item");

			if (Items.Contains(item))
				throw new ArgumentException(string.Format(System.Globalization.CultureInfo.CurrentCulture,
					Errors.ToolWindowExists, item.Guid.ToString("B")), "item");

			if (this.Contains(item.Guid))
				throw new ArgumentException(string.Format(System.Globalization.CultureInfo.CurrentCulture,
					Errors.ToolWindowGuidExists, item.Guid.ToString("B")), "item");

			DocProjectEnvironment.RegisterToolWindow(item);

			base.InsertItem(index, item);
		}

		protected override void SetItem(int index, ToolWindow item)
		{
			if (item == null)
				throw new ArgumentNullException("item");

			ToolWindow old = this.Items[index];

			if (old == item)
				return;

			if (Items.Contains(item))
				throw new ArgumentException(string.Format(System.Globalization.CultureInfo.CurrentCulture,
					Errors.ToolWindowExists, item.Guid.ToString("B")), "item");

			if (this.Contains(item.Guid))
				throw new ArgumentException(string.Format(System.Globalization.CultureInfo.CurrentCulture,
					Errors.ToolWindowGuidExists, item.Guid.ToString("B")), "item");

			DocProjectEnvironment.UnregisterToolWindow(old);

			DocProjectEnvironment.RegisterToolWindow(item);

			base.SetItem(index, item);
		}

		protected override void RemoveItem(int index)
		{
			ToolWindow item = this.Items[index];

			DocProjectEnvironment.UnregisterToolWindow(item);

			base.RemoveItem(index);
		}

		protected override void ClearItems()
		{
			foreach (ToolWindow item in this.Items)
				DocProjectEnvironment.UnregisterToolWindow(item);

			base.ClearItems();
		}
		#endregion
	}
}
